package com.zhanghe.study.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Set;

/**
 * @author: zhanghe
 * @date: 2020/6/17 19:57
 */
public class TestClient {
    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        // 设置为非阻塞
        socketChannel.configureBlocking(false);

        // 注册监听的事件
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        // 绑定8080端口
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey selectionKey : selectionKeys) {
                if (selectionKey.readyOps() == SelectionKey.OP_CONNECT) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    if (client.isConnectionPending()) {
                        try {
                            // 完成连接套接字
                            client.finishConnect();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            byteBuffer.put("连接成功".getBytes());
                            byteBuffer.flip();
                            client.write(byteBuffer);
                        } catch (Exception e) {

                        }
                    }
                    client.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.readyOps() == SelectionKey.OP_READ) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int count = client.read(buffer);
                    if (count > 0) {
                        buffer.flip();
                        Charset charset = Charset.defaultCharset();
                        String message = String.valueOf(charset.decode(buffer).array());
                        System.out.println("接收到消息" + message);
                    }
                }
                selectionKeys.clear();
            }
        }

    }
}
